#include <stdlib.h>
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include <opencv/highgui.h>
#include <time.h>

using namespace cv;

int main(int argc, char **argv)
{
  /* initialize camera */
  VideoCapture capture = VideoCapture(0);

  Mat base;
  Mat prev;
  Mat frame;
  Mat jpeg;
  Mat diff;
  Mat jpeg_diff;

  int key = 0;

  if(!capture.isOpened()) {
    fprintf( stderr, "Cannot open initialize webcam!\n");
    return 1;
  }

  cvNamedWindow("Original", CV_WINDOW_AUTOSIZE);
  cvNamedWindow("JPEG", CV_WINDOW_AUTOSIZE);
  cvNamedWindow("Difference", CV_WINDOW_AUTOSIZE);
  cvNamedWindow("Reconstructed", CV_WINDOW_AUTOSIZE);
  
  while(true) {
    if(capture.read(frame)) {
      break;
    }
  }
  jpeg_diff = frame.clone();

  while( key != 'q'){

    prev = frame.clone();

    /* get a frame */
    if(!capture.read(frame)) {
      continue;
    }

    vector<uchar> buf;
    if(!imencode("*.png",frame,buf)) {
      break;
    }
    jpeg = imdecode(buf,1);

    diff = frame - prev;

    vector<uchar> buf1;
    if(!imencode("*.png",diff,buf1)) {
      break;
    }
    jpeg_diff = imdecode(buf1,1) + jpeg_diff;

    /* display current frame */
    imshow("Original", frame);
    imshow("JPEG", jpeg);
    imshow("Difference", diff);
    imshow("Reconstructed", jpeg_diff);

    printf("JPEG: %i\t Difference: %i\n", (int)buf.size(), (int)buf1.size());
    /* exit if user press 'q' */
    key = cvWaitKey(1);
    fflush(stdout);
  }

  /* free memory */
  cvDestroyWindow("Original");
  cvDestroyWindow("JPEG");
  cvDestroyWindow("Difference");
  cvDestroyWindow("Reconstructed");

  return 0;
}
